package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.model.Account;
import com.rongke.model.Muser;
import com.rongke.model.Withdrawals;
import com.rongke.redis.CacheUtil;
import com.rongke.service.AccountService;
import com.rongke.service.MuserService;
import com.rongke.service.WithdrawalsService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @WithdrawalsController
 * @提现Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/withdrawals")
@Transactional
@CrossOrigin
public class WithdrawalsController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private WithdrawalsService withdrawalsService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private AccountService accountService;
    @Autowired
    private MuserService muserService;
    /**
     * @添加提现
     * @param withdrawals
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public JsonResp addWithdrawals(@RequestBody Withdrawals withdrawals){
        log.debug("添加提现");
        withdrawals.setGmtDatetime(new Date());
        withdrawalsService.insert(withdrawals);
        return JsonResp.ok(withdrawals);
    }

    /**
     * @获取提现记录列表
     * @param withdrawals
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateWithdrawals(@RequestBody Withdrawals withdrawals){
        log.debug("修改提现");
        withdrawals.setUptDatetime(new Date());
        withdrawalsService.updateById(withdrawals);
        return JsonResp.ok(withdrawals);
    }
    /**
     * @根据id查找提现
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectWithdrawals(Long id){
        log.debug("查找提现");
        Withdrawals withdrawals = withdrawalsService.selectById(id);
        return JsonResp.ok(withdrawals);
    }

    /**
     * @获取支付宝账号和用户真实性名
     * @param token 令牌
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/findAlipayNo", method = RequestMethod.GET)
    public JsonResp findAlipayNo(String token){
        log.debug("获取支付宝账号和用户真实性名");
        if(!cacheUtil.hasKey(token)){
            return JsonResp.fa(muserService.LOGINSTR);
        }
        Long muserId=Long.valueOf(cacheUtil.get(token));
        EntityWrapper<Withdrawals> ew=new EntityWrapper<>();
        ew.eq("muser_id",muserId);
        ew.orderBy("gmt_datetime",false);
        List<Withdrawals> withdrawalses=withdrawalsService.selectList(ew);
        Map map=new HashMap();
        if(!withdrawalses.isEmpty()){
            map.put("realName",withdrawalses.get(0).getRealName());
            map.put("alipayNo",withdrawalses.get(0).getAlipayNo());
        }else {
            map.put("realName","");
            map.put("alipayNo","");
        }
        return JsonResp.ok(map);
    }





    /**
     *  提现到支付宝
     * @param alipayNo 支付宝账号
     *        realName  真实姓名
     *         money    提现金额
     * @return 返回值JsonResp
     * @修改密码
     */
    @RequestMapping(value = "/withdrawals", method = RequestMethod.GET)
    public JsonResp withdrawals(String token, String alipayNo, String realName,Double money) {
        log.debug("提现到支付宝");
        if (!cacheUtil.hasKey(token)) {
            return JsonResp.fa(muserService.LOGINSTR);
        }
        Long muserId=Long.valueOf(cacheUtil.get(token));
        Muser muser=muserService.selectById(muserId);
        muser.setRealName(realName);
        muserService.updateById(muser);
        EntityWrapper<Account>  ew=new EntityWrapper<>();
        ew.eq("muser_id",muserId);
        Account account=accountService.selectOne(ew);
//        BigDecimal totalMoney=new BigDecimal(String.valueOf(money)).divide(new BigDecimal(0.9),2,BigDecimal.ROUND_HALF_UP);
        BigDecimal totalMoney=new BigDecimal(String.valueOf(money));
        if(account.getDuoBi().compareTo(totalMoney)<0){
            return JsonResp.fa("账号余额不足");
        }else {
            account.setDuoBi(account.getDuoBi().subtract(totalMoney));
            accountService.updateById(account);
        }
        //**********流水明细**************//
        Withdrawals withdrawals=new Withdrawals();
        withdrawals.setMuserId(muserId);
        withdrawals.setMoney(new BigDecimal(money).multiply(new BigDecimal("0.9")));
        withdrawals.setAlipayNo(alipayNo);
        withdrawals.setRealName(realName);
        withdrawals.setStatus(1);
        withdrawals.setTitle("提现"+money);
        withdrawals.setGmtDatetime(new Date());
        withdrawalsService.insert(withdrawals);
        return JsonResp.ok();
    }


    /**
     * @根据条件查找获取提现列表
     * @param withdrawals
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/selectByCondition", method = RequestMethod.POST)
    public JsonResp selectWithdrawalsByCondition(@RequestBody Withdrawals withdrawals){
        log.debug("根据条件查找获取提现列表");
        if(withdrawals==null)
            return JsonResp.toFail("参数不能为空");
        List<Withdrawals> withdrawalsList=withdrawalsService.selectByCondition(withdrawals);
        return JsonResp.ok(withdrawalsList);
    }


    /**
     * @后台改变提现状态（同意、拒绝）
     * @param type 2已通过3拒绝4已打款
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/agreeWithDrawals", method = RequestMethod.GET)
    public JsonResp agreeWithDrawals(Long id,Integer type){
        log.debug("后台改变提现状态（同意、拒绝）");
        Withdrawals withdrawals=withdrawalsService.selectById(id);
        if(type==2){
            if(withdrawals.getStatus()==1){
                withdrawals.setStatus(type);
            }else {
                return JsonResp.fa("无效操作");
            }
        }else if(type==3){
            if(withdrawals.getStatus()==1){
                withdrawals.setStatus(type);
            }else {
                return JsonResp.fa("无效操作");
            }

        }else if(type==4) {
            if(withdrawals.getStatus()==2){
                withdrawals.setStatus(type);
            }else {
                return JsonResp.fa("无效操作");
            }
        }
      withdrawalsService.updateById(withdrawals);
        return JsonResp.ok();
    }


    /**
     * @根据条件查找获取提现列表
     * @param withdrawals
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/selectWithdrawalsList", method = RequestMethod.POST)
    public JsonResp selectWithdrawalsList(Withdrawals withdrawals, Page page){
        log.debug("根据条件查找获取提现列表");
        Map map=new HashMap();
        if(withdrawals!=null){
            if(withdrawals.getStatus()!=null && !"".equals(String.valueOf(withdrawals.getStatus()))){
                map.put("status",withdrawals.getStatus());
            }
        }
        Integer startIndex=(page.getCurrent()-1)*page.getSize();
        map.put("startIndex",startIndex);
        map.put("size",page.getSize());
        List<Withdrawals> withdrawalsList=withdrawalsService.selectWithdrawalsList(map);
        Integer size=withdrawalsService.selectWithdrawalsListSize(map);
        page.setRecords(withdrawalsList);
        page.setTotal(size);
        return JsonResp.ok(page);
    }



}
